package com.desire.homework;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 求123456789 字符串1..9 之间不改数字位置随机+-要求表达结果和为100,写出这样表达式
 *
 * @author desire
 */
public class _22_1到9随机组合相加减等于100_面试题 {
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        int index = 0;
        while (true) {
            Random random = new Random();
            // 首位 必须是 1   不能是 +1  或者 -1
            StringBuilder formula = new StringBuilder("1");
            String[] symbol = new String[]{"", "+", "-"};
            for (int i = 2; i <= 9; i++) {
                formula.append(symbol[random.nextInt(symbol.length)].concat(String.valueOf(i)));
            }
            // System.out.printf("%s", formula);
            Pattern pattern = Pattern.compile("-?\\d+");
            Matcher matcher = pattern.matcher(formula);

            int sum = 0;
            while (matcher.find()) {
                int num = Integer.parseInt(matcher.group());
                sum += num;
            }
            if (sum == 100) {
                //System.out.printf("%d、%s = 100%n", ++index, formula);
                set.add(formula.toString());
            }
            if (set.size() == 11) {
                break;
            }
        }
        for (String s : set) {
            System.out.printf("%s = 100%n", s);
        }
    }
}
